from db.metastore import connect_with_pocketbase, user_auth_via_client, client_create_new, client_delete_record, \
    client_fetch_from, client_fetch_full_list_from, client_update_to
from application.handle_exception import pb_operation_exception
from domain.authentication import User
from domain.envd import EnvdInDB, EnvdBuild


async def add_new_envd_metadata_record(
        metadata: EnvdInDB,
        user: User
):
    with connect_with_pocketbase() as db_client:
        _ = user_auth_via_client(
            client=db_client,
            user=user
        )
        new_record = await client_create_new(
            client=db_client,
            collection="envds",
            data=metadata.dict()
        )
        if not new_record:
            raise pb_operation_exception
    return new_record


async def view_envd_metadata(
        record_id: str,
        user: User
):
    with connect_with_pocketbase() as db_client:
        _ = user_auth_via_client(
            client=db_client,
            user=user
        )
        if record_id is None:
            record_response = await client_fetch_full_list_from(
                client=db_client,
                collection="envds"
            )
        else:
            record_response = await client_fetch_from(
                client=db_client,
                collection="envds",
                target_id=record_id
            )

    return record_response


async def update_envd_metadata(
        user: User,
        update_record_id: str,
        new_envd_build: EnvdBuild,
):
    with connect_with_pocketbase() as db_client:
        _ = user_auth_via_client(
            client=db_client,
            user=user
        )
        record_response = await client_fetch_from(
            client=db_client,
            collection="envds",
            target_id=update_record_id
        )
        record_dict = record_response.__dict__
        new_build_meta = EnvdInDB(
            project_name=record_dict['project_name'],
            uuid=record_dict['uuid'],
            build_metadata=new_envd_build
        )
        update_record_response = await client_update_to(
            client=db_client,
            collection="envds",
            target_id=update_record_id,
            data=new_build_meta.dict()
        )
        if not update_record_response:
            raise pb_operation_exception
    return update_record_response


async def delete_metadata_record(
        record_id: str,
        user: User
):
    with connect_with_pocketbase() as db_client:
        _ = user_auth_via_client(
            client=db_client,
            user=user
        )
        null_content_response = await client_delete_record(
            client=db_client,
            collection="envds",
            target_id=record_id
        )
        if not null_content_response:
            raise pb_operation_exception
    return null_content_response
